package lsystem

/**
 * User: koeppelad
 * Date: 4/14/11
 * Time: 8:29 PM
 */
import scala.collection.immutable.Set
import scala.util.matching.Regex
import java.util.regex.Pattern

case class ProductionRule(predecessor: Regex, successors: Set[(String, Double)])
{
  def this(predecessor: Regex, successors: (String, Double)*) =
		this(predecessor, Set() ++ successors)

  def this(predecessor: Regex, successor: String) =
		this(predecessor, Set[(String, Double)]((successor, 1.0)))

	def this(predecessor: String, successors: (String, Double)*) =
		this(Pattern.quote(predecessor).r, Set() ++ successors)  //for some stupid reason it complains if I just try to pass successors

	def this(predecessor: String, successor: String) =
		this(Pattern.quote(predecessor).r, successor)

	def selectSuccessor: String =
	{
		val total = successors.foldRight (0.0)({(succ, sum) => sum + succ._2})
		val rand = math.random
		var sum = 0.0
		for((succ, prob) <- successors)
		{
			sum += prob
			if(sum / total > rand)
				return succ
		}
		throw new Exception("sum / total != 1, Differing sums, " +
      "this should never happen!")
	}
}